from urllib import urlopen, urlencode
import time, datetime

BASE_URL = "http://services.tvrage.com/tools/quickinfo.php"

def get_episode_info(data):
	if not data.has_key('Episode Info'):
		return None, None
	title, date = data['Episode Info'][1:3]
	try:
		try:
			date = time.strptime(date, "%b/%d/%Y")
		except ValueError:
			date = time.strptime(date, "%d/%b/%Y")
		date = datetime.date(date.tm_year, date.tm_mon, date.tm_mday)
	except ValueError:
		date = None
	return title, date

def read(show, ep = None):
	args = {
		'show': show.encode('UTF-8'),
	}
	if ep:
		args['ep'] = ep
	url = BASE_URL + "?" + urlencode(args)
	data = {'url':url}
	for line in urlopen(url):
		if line.startswith('No Show Found'):
			return None
		try:
			key, value = line[:-1].split("@", 1)
			if value.find('^') >= 0:
				value = value.split('^')
			data[key] = value
		except ValueError:
			pass
	return data

SHOWS = [
	'24',
	'30 Rock',
	'Andy Barker, P.I.',
	'Battlestar Galactica',
	'Better Off Ted',
	'Bionic Woman',
	'Bones',
	'Breaking Bad',
	'Burn Notice',
	'Californication',
	'Castle',
	'Chuck',
	'Damages',
	'Deadwood',
	'Dexter',
	'Doctor Who',
	'Dollhouse',
	'Drive',
	'Eleventh Hour',
	'Eureka',
	'Fear Itself',
	'FlashForward',
	'Flashpoint',
	'Fringe',
	'Gilmore Girls',
	'Heroes',
	'Hung',
	'In Plain Sight',
	'John from Cincinnati',
	'Journeyman',
	'Kings',
	'Kyle XY',
	'Legend of the Seeker',
	'Leverage',
	'Lie to Me',
	'Life',
	'Life On Mars (US)',
	'Lost',
	'Mad Men',
	'Masters of Horror',
	'Masters of Science Fiction',
	'Medium',
	'Merlin',
	'MythBusters',
	'Nip/Tuck',
	'NUMB3RS',
	'Penn & Teller: Bullshit!',
	'Prison Break',
	'Psych',
	'Pushing Daisies',
	'Reaper',
	'ReGenesis',
	'Reno 911!',
	'Rome',
	'Royal Pains',
	'Sanctuary',
	'Saving Grace',
	'Secret Diary of a Call Girl',
	'Sons of Anarchy',
	'Supernatural',
	'Terminator: The Sarah Connor Chronicles',
	'The 4400',
	'The Colbert Report',
	'The Collector',
	'The Daily Show',
	'The IT Crowd',
	'The Kill Point',
	'The Mentalist',
	'The Middleman',
	'The Shield',
	'True Blood',
	'United States of Tara',
	'V',
	'Veronica Mars',
	'Warehouse 13',
	'Weeds',
	'The Vampire Diaries',
	'The Unusuals',
]

__ALL__ = ['BASE_URL', 'SHOWS', 'read']
